<?php

// 注册
// POST member.reg

namespace app\api\resource\member;
use think\Db;
use think\facade\Config;
use app\common\validate\Member as MemberValidate;
use app\common\lib\SmsCode as SmsCodeCommonLib;
use app\common\lib\Yp as YpCommonLib;

class Reg
{
    // 方法
    public $_method = ['POST'];
    // 前置
    public $_pre    = [];
    // 描述
    public $_description = '注册';
    // 参数
    public $_param  = [
        'reffer' => '推荐码,可选',
        'mobile' => '手机号',
        'code'   => '短信码',
    ];

    public function run(&$request)
    {
        $params   = $request->param();
        $validate = new MemberValidate;
        if ( !$validate->scene('reg')->check($params) ) {
            $errMsg = $validate->getError();
            return [422,$errMsg];
        }
        
        $expire = time() + 86400 * 3;

        $reffer = $request->param('reffer/s','','trim');
        if ( !empty($reffer) ) {
            $reffer = base64_decode($reffer . '==');
            if ( !is_numeric($reffer) ) return [422,'推荐码无效[1]'];
            $mb = Db::name('member')->where('id',$reffer)->find();
            if ( is_null($mb) ) return [422,'推荐码无效[2]'];
            $data['pid'] = $reffer;
            $expire += 86400 * 5;
        }

        // 短信码
        $mobile = $params['mobile'];
        $alias  = 'reg';
        $code   = $params['code'];
        $res = SmsCodeCommonLib::check($mobile,$alias,$code);
        if ('not_found'  == $res) return [400,'未发送短信码'];
        if ('code_error' == $res) return [400,'短信码不正确'];

        $ret = Db::name('member')->where('mobile',$mobile)->field('id')->find();
        if ( !is_null($ret) ) return [400,'该手机号已被注册'];

        $password = rand(100000,999999);

        $data['mobile']      = $mobile;
        $data['nickname']    = Config::get('sg.default_nickname');
        $data['headimgurl']  = Config::get('sg.default_headimgurl');
        $data['password']    = md5($password);
        $data['expire']      = $expire;
        // $data['pid']         = 0;
        $data['status']      = 0;
        $data['create_time'] = time();
        $num = Db::name('member')->insert($data);
        if ($num > 0) {
            // 发送通知短信
            $yp = new YpCommonLib;
            $yp->sendNotice($mobile,$password);

            return [201,'注册成功'];
        } else {
            return 500;
        }
    }
}
